package com.yc.tomcat.impl;

import com.yc.tomcat.Cookie;
import com.yc.tomcat.HttpServletRequest;
import com.yc.tomcat.HttpSession;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HttpServletRequestImpl implements HttpServletRequest {

    private InputStream in;
    private String requestURI;
    private String protocol;
    private String method;
    private Map<String, String> headerMap = new HashMap<>();

    private HttpSession session;
    // 会话容器
    public static Map<String,HttpSession> sessionMap = new HashMap<>();

    // 参数集合
    private Map<String, List<String>> parameterMap = new HashMap<>();

    public HttpServletRequestImpl(Socket socket) throws IOException {
        this.in = socket.getInputStream();

//        byte[] bytes = new byte[1024];
//        int count = in.read(bytes);
//        // System.out.println(new String(bytes,0,count));
//        String reqString = new String(bytes, 0, count);
        // 按字节读取 请求头数据
        String reqString = readHeader(in);

        String[] lines = reqString.split("\r\n");
        // 解析请求头
        for (int i = 0; i < lines.length; i++) {
            if (i == 0) {
                // 请求头行
                String[] items = lines[i].split(" ");
                this.method = items[0];
                this.requestURI = items[1];
                this.protocol = items[2];

                if (this.requestURI.contains("?")) {
                    int i1 = this.requestURI.indexOf("?");
                    String queryString = this.requestURI.substring(i1 + 1);
                    // 对queryString解码
                    queryString = URLDecoder.decode(queryString, "utf-8");

                    this.requestURI = this.requestURI.substring(0, i1);
                    parseParameter(queryString);
                }
            } else if (lines[i].isEmpty()) {
                // 空行 => 分隔行
                break;
            } else {
                // 请求头
                String[] items = lines[i].split(": ");
                headerMap.put(items[0], items[1]);
            }
        }
        System.out.println(this);

        //读取请求体
        if("POST".equals(method)){
            parseBody(in);
        }

        // 获取或创建会话对象
        Cookie[] cookies = getCookies();
        //HttpSession session = null;
        if(cookies!=null){
            String sessionId = null;
            for (Cookie cookie : cookies) {
                if("JSESSIONID".equals(cookie.getName())){
                    sessionId = cookie.getValue();
                    break;
                }
            }
            if(sessionId != null){
                session = sessionMap.get(sessionId);
            }
        }
        if(session == null){
            // 創建會話對象
            session = new HttpSessionImpl();
            // 保存到會話容器
            sessionMap.put(session.getId(), session);
        }
    }

    private void parseBody(InputStream in) throws IOException {
        String contentType = headerMap.get("Content-Type");
        if("application/x-www-form-urlencoded".equals(contentType)){
            // 表单提交, body的内容参考: a=100&b=abc
            String length = getHeader("Content-Length");
            long size = Long.parseLong(length);
            StringBuilder buffer = new StringBuilder();
            char c;
            for (int i = 0; i < size; i++) {
                c = (char)in.read();
                buffer.append(c);
            }
            System.out.println("请求体内容:");
            System.out.println(buffer);
            // 解析 body 中请求参数
            parseParameter(buffer.toString());
        } else if("multipart/form-data".equals(contentType)){
            // 文件上传
            // 判断长度: 低于某个阈值, 保存到内存(StringBuilder), 否则保存到磁盘临时文件
            // 读取 Content-Type 的分隔线, 使用分隔线切割 请求体
            // 分别读取每个字段的值
        } else {
            // TODO 其它类型的body解析
        }


    }

    // 获取请求头数据
    private String readHeader(InputStream in) throws IOException {
        StringBuilder buffer = new StringBuilder();
        char c;
        while(true){
            c = (char)in.read();
            if(c == '\r'){  //  \r 回车, \n 换行
                buffer.append(c);
                c = (char)in.read();
                buffer.append(c);
                c = (char)in.read();
                if(c == '\r'){    // 空行, 表示请求头结束
                    buffer.append(c);
                    c = (char)in.read();
                    buffer.append(c);
                    break;
                }
            }
            buffer.append(c);
        }
        return buffer.toString();
    }

    // queryString => a=100&b=abc&a=200
    public void parseParameter(String queryString) {
        String[] items = queryString.split("&");
        for (String item : items) {
            String[] nameAndValue = item.split("=");
            String value;
            if (nameAndValue.length == 2) {
                value = nameAndValue[1];
            } else {
                value = "";
            }
            List<String> values = parameterMap.get(nameAndValue[0]);
            // 如果 values 是空, 说明是第一次添加该参数值
            if (values == null) {
                // 创建值集合
                values = new ArrayList<>();
                parameterMap.put(nameAndValue[0], values);
            }
            values.add(nameAndValue[1]);
        }
        System.out.println(parameterMap);
    }

    @Override
    public InputStream getInputStream() {
        return in;
    }

    @Override
    public String getMethod() {
        return method;
    }

    @Override
    public String getRequestURI() {
        return requestURI;
    }

    @Override
    public String getProtocol() {
        return protocol;
    }

    @Override
    public String getHeader(String name) {
        return headerMap.get(name);
    }

    @Override
    public Cookie[] getCookies() {
        String cookie = getHeader("Cookie");
        if(cookie == null){
            return null;
        }
        String[] items = cookie.split("; ");
        List<Cookie> list = new ArrayList<>();
        for (String item : items) {
            String[] nameAndValue = item.split("=");
            Cookie c = new CookieImpl(nameAndValue[0],nameAndValue[1]);
            list.add(c);
        }
        return list.toArray(new Cookie[0]);
    }

    @Override
    public String getRequestedSessionId() {
        return session.getId();
    }

    @Override
    public String getParameter(String name) {
        List<String> values = parameterMap.get(name);
        if (values != null && values.isEmpty() == false) {
            return values.get(0);
        }
        return null;
    }

    // a=100&a=200&a=300 => getParameterValues("a") => [100,200,300]
    @Override
    public String[] getParameterValues(String name) {
        List<String> values = parameterMap.get(name);
        if(values == null){
            return null;
        } else {
            // 集合转数组
            return values.toArray(new String[0]);
        }
    }

    @Override
    public String getQueryString() {
        return null;
    }

    @Override
    public HttpSession getSession() {
        return session;
    }

    @Override
    public String toString() {
        return "HttpServletRequestImpl{" +
                "in=" + in +
                ", requestURI='" + requestURI + '\'' +
                ", protocol='" + protocol + '\'' +
                ", method='" + method + '\'' +
                ", headerMap=" + headerMap +
                '}';
    }

    // setCharacterEncoding
}
